<style media="screen">
  div > h1 {
    margin-bottom: 20px;
  }
  .form {
    width: 50%;
}
.content-text {
  margin: 10px;
}
</style>
<template>
    <div>
      <!-- <h1>使用iView自带的文件上传组件，方便快捷</h1>
      <Upload
          multiple
          type="drag"
          action="//jsonplaceholder.typicode.com/posts/">
          <div style="padding: 20px 0">
              <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
              <p>点击或将文件拖拽到这里上传</p>
          </div>
      </Upload> -->
      <div class="form">
        <i-form >
          <Form-item label="上传文本" prop="text">
              <i-input v-model="text"  type="textarea" @on-blur="validateText" :autosize="{minRows: 2,maxRows: 5}" placeholder="文本上传"></i-input>
          </Form-item>
          <Form-item>
              <i-button type="primary" @click.native="handleSubmit()" :disabled="isSubmit1">提交</i-button>
              <i-button type="ghost" @click.native="handleReset()" style="margin-left: 8px">重置</i-button>
          </Form-item>
        </i-form>
        <div>
          <h3>文本hash:</h3>
          <p class="content-text"> {{ textHash }}</p>
          <div v-if="txResult !== null">
            <h2 style="margin-bottom: 10px;">交易结果：</h2>
            <p style="font-weight: bold;">交易id:</p> 
            <p class="content-text">{{ txResult.transaction.id }}</p> 
            <p style="font-weight: bold;">存储内容:</p> 
            <p class="content-text">{{ txResult.transaction.resume }}</p> 
            <p style="font-weight: bold;">时间戳:</p> 
            <p class="content-text">{{ txResult.transaction.timestamp }}</p> 
            <p style="font-weight: bold;">手续费:</p> 
            <p class="content-text">{{ txResult.transaction.fee }}</p> 
            <p style="font-weight: bold;">发起者id:</p> 
            <p class="content-text">{{ txResult.transaction.senderId }}</p> 
          </div>
        </div>
      </div>
      <div style="margin-top: 50px;">
          <Upload
              :before-upload="handleUpload"
              action="//jsonplaceholder.typicode.com/posts/">
              <Button type="primary" icon="ios-cloud-upload-outline">选择图片上传</Button>
          </Upload>
          <div v-if="file !== null">
            <h3>文件名：</h3>{{ file.name }} 
            <Button type="success" @click="upload" :disabled="isSubmit2" :loading="loadingStatus">{{ loadingStatus ? '正在上传' : '点击开始上传' }}</Button>
          </div>
          <h3>文件hash：</h3>
          <p class="content-text" v-if="fileHash !== ''"> {{ fileHash }} </p>
          <div>
          <div v-if="txPicResult !== null">
            <h2 style="margin-bottom: 10px;">交易结果：</h2>
            <p style="font-weight: bold;">时间戳:</p> 
            <p class="content-text">{{ txPicResult.transaction.timestamp }}</p> 
            <p style="font-weight: bold;">存储内容:</p> 
            <p class="content-text">{{ txPicResult.transaction.resume }}</p> 
            <p style="font-weight: bold;">交易id:</p> 
            <p class="content-text">{{ txPicResult.transaction.id }}</p> 
            <p style="font-weight: bold;">手续费:</p> 
            <p class="content-text">{{ txPicResult.transaction.fee }}</p> 
            <p style="font-weight: bold;">发起者id:</p> 
            <p class="content-text">{{ txPicResult.transaction.senderId }}</p> 
          </div>
        </div>
      </div>
      <!-- <div style="margin-top: 100px;">
        <Upload
              :before-upload="handleUpload"
              action="//jsonplaceholder.typicode.com/posts/">
              <Button type="ghost" icon="ios-cloud-upload-outline">选择图片验证</Button>
          </Upload>
          <div v-if="file !== null">文件名: {{ file.name }} <Button type="text" @click="upload" :loading="loadingStatus">{{ loadingStatus ? 'Uploading' : 'Click to upload' }}</Button></div>
      </div> -->
    </div>
</template>
<script>
import crypto from 'crypto';

    export default {
      data () {
          return {
              file: null,
              loadingStatus: false,
              text: '',
              textHash: '',
              fileHash: '',
              isSubmit1: false,
              isSubmit2: false,
              txResult: null,
              txPicResult: null,
          }
      },
      methods: {
         /**
            Liens使用的是sha256Hash算法
            通过Crypto模块，简单加密生成一个哈希值：
            var hash = crypto.createHash('sha256').update(data).digest()

            crypto.createHash('sha256')先用sha256算法创建一个Hash实例
            接着使用.update(data)接受明文data数据
            最后调用.digest()方法，获得加密字符串，即密文
            **/
          validateText() {
            //TO-FIX json to restrict form of string
            //var str = " test,.23@#!$$k~!  @#$%^&*()(_+-=|\{}[]';:,./<>??gg  g~```hello, ，  world ! ！: ：";
            
            var str = this.text;
            if(str){
              console.log("str1: " + str);

              str=str.replace(/[\ |\~|\`|\!|\@|\#|\$|\%|\^|\&|\*|\(|\)|\-|\_|\+|\=|\||\\|\[|\]|\{|\}|\;|\:|\"|\'|\,|\<|\.|\>|\/|\?|\、|\，|\。|\？|\《|\》|\；|\‘|\：|\“|\【|\】|\{|\}|\·|\~|\！|\￥|\……|\（|\）|\——|\+]/g,""); 
              //console.log("str2: " + str);

              var hash1 = crypto.createHash('sha256').update(str, 'utf8').digest().toString('hex');
              //var hash2 = crypto.createHash('sha256').update("I", 'utf8').digest().toString('hex');
              this.textHash = hash1;
              
              //console.log("str2 hash256: " + hash1);
            }
          },
          handleSubmit(data) {
              this.isSubmit1 = true; //禁用
              var textHash = this.textHash;
              // var form = new FormData();
              // form.append('resume',textHash);
              // form.append('secret','AiU5S06&YaxbFL$h%aHgJaNv2fX6ho8H');
              // console.log(textHash);
              if(textHash){
                this.$http
                  .put('/api/transactions/resume',{
                    "resume": textHash,
                    "secret": "AiU5S06&YaxbFL$h%aHgJaNv2fX6ho8H" // 上帝账号
                  })
                  // ({
                  //   method: 'put',
                  //   url: '/api/transactions/resume',
                  //   // headers: {
                  //   //   'Content-Type': 'application/x-www-form-urlencoded; '
                  //   // },
                  //   data:  form,
                  //   // params: { 
                  //   //   "resume": textHash,
                  //   //   "secret": "AiU5S06&YaxbFL$h%aHgJaNv2fX6ho8H" // 上帝账号
                  //   // }
                  // })
                  .then(response => {
                    if(response.data.success == true){
                      // console.log(response.data);
                      this.txResult = response.data;
                      this.isSubmit1 = false;
                      this.$Message.success('上传成功');
                    }else {
                      this.$Message.error(response.data.error);
                      this.isSubmit1 = false;
                    }
                  })
                  // 注册 /api/accounts/open
                  // this.$http
                  // .post('/api/accounts/open',{
                  //   "secret": "123456" 
                  // })
                  // .then(response => {
                  //   console.log(response);
                  //   this.isSubmit1 = false;
                  // })
              }
              
          },
          handleReset(name) {
              this.text = '';
              this.textHash = '';
              //this.$Message.warning('这是一条警告的提示');
          },

          // 图片转码
          handleUpload (file) {
              this.isSubmit2 = true; // 转格式完成前禁用
              var reader = new FileReader();
              var fileBase64;
              this.file = file;
              var this_ = this; // 取代异步file读取时的this
              var imgUrlBase64;
              // var imgText;
              if(file){
                //将文件以Data URL形式读入页面  
                imgUrlBase64 = reader.readAsDataURL(this.file);
                //imgText = reader.readAsText(file);
                //console.log(this.file);
                //console.log(this.fileHash !== '');
                reader.onload = function (e) {
                  //var ImgFileSize = reader.result.substring(reader.result.indexOf(",") + 1).length;//截取base64码部分（可选可不选，需要与后台沟通）
                  
                  //执行上传操作
                  fileBase64 = reader.result;
                  // console.log(fileHash);
                  var hash2 = crypto.createHash('sha256').update(fileBase64, 'utf8').digest().toString('hex');
                  this_.fileHash = hash2;
                  this_.isSubmit2 = false;
                  //console.log(this_.fileHash);
                  //console.log(this.fileHash !== '');
                }
              
              }
              return false;
          },
          // 发起交易
          upload () {
              this.loadingStatus = true;
              this.isSubmit2 = true; //禁用
              var fileHash = this.fileHash;
              // console.log(textHash);
              if(fileHash){
                this.$http
                  .put('/api/transactions/resume',{
                    "resume": fileHash,
                    "secret": "AiU5S06&YaxbFL$h%aHgJaNv2fX6ho8H" // 上帝账号
                  })
                  .then(response => {
                    if(response.data.success == true){
                      // console.log(response.data);
                      this.txPicResult = response.data;
                      this.loadingStatus = false;
                      // this.fileHash = '';
                      // this.file = null;
                      this.isSubmit2 = false;
                      this.$Message.success('上传成功');
                    }else {
                      this.$Message.error(response.data.error);
                      this.isSubmit2 = false;
                      this.loadingStatus = false;
                      
                    }
                    
                  })
                  // 注册 /api/accounts/open
                  // this.$http
                  // .post('/api/accounts/open',{
                  //   "secret": "123456" 
                  // })
                  // .then(response => {
                  //   console.log(response);
                  //   this.isSubmit1 = false;
                  // })
              }
              
          },
          
      }
    }
</script>
